﻿<?php
	session_start();
	
	function generateRandomString($length = 10) {
	    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
	    $randomString = '';
	    for ($i = 0; $i < $length; $i++) {
		$randomString .= $characters[rand(0, strlen($characters) - 1)];
	    }
	    return $randomString;
	}
	
	include("sendmail.php");

	if(isset($_GET['key']))
	{
		$key = $_GET['key'];
		include 'config.php';
		mysqli_set_charset($con, 'utf8');
		
		// Check connection
		if (mysqli_connect_errno())
		{
			echo "Failed to connect to MySQL: " . mysqli_connect_error();
		}
		
		$newpassword = $_POST['password'];
		$md5pw = md5($newpassword);
		$sql = "UPDATE `User` SET `Password` =  '$md5pw', `ResetKey` = NULL WHERE `ResetKey` = '$key'";
		
		if (!mysqli_query($con,$sql))
		{
			die('Error: ' . mysqli_error($con));
		}
		
		mysqli_close($con);

		$_SESSION['message'] = "Ditt lösenord har blivit ändrat. Du kan nu logga in.";
		header ("Location: index.php");
	}
	else
	{
		$con=mysqli_connect("mysql12.citynetwork.se","108497-hl64722","Kanin1989","108497-salesmakeover");
		mysqli_set_charset($con, 'utf8');
		
		// Check connection
		if (mysqli_connect_errno())
		{
			echo "Failed to connect to MySQL: " . mysqli_connect_error();
		}
		$username = $_POST['username'];
		$resetkey = generateRandomString();

		$sql = "UPDATE `User` SET `ResetKey` =  '$resetkey' WHERE `Login` = '$username'";
		
		if (!mysqli_query($con,$sql))
		{
			die('Error: ' . mysqli_error($con));
		}
		
		$sql2 = "SELECT Name FROM User WHERE Login = '$username'";
		
		$result = mysqli_query($con,$sql2);
		$count=mysqli_num_rows($result);
		if($count == 1)
		{
			$row = mysqli_fetch_array($result);
			
			$userrealname = $row['Login'];
		}
		
		
		mysqli_close($con);
		
		sendNewAccountInfo(login, $userrealname, $resetkey);
		
		$_SESSION['message'] = "Kolla din mail och följ instruktionerna.";
		header ("Location: index.php");
	}
	
	

	
?>